package com.catchu.web;

import com.catchu.domain.User;
import com.catchu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.validation.Valid;
import java.util.List;

/**
* 用户控制器
* @author ljz on 2018/4/10 0010
*/
@Controller
@RequestMapping("/api/v2")
public class UserWebController2 {

    @Autowired
    private UserService userService;

    /**
     * 获取用户列表
    * @author ljz on 2018/4/10 0010
    * @param
    * @return
    */
    @RequestMapping(value="/findList",method= RequestMethod.GET)
    public String findList(Model model){
        User user = new User();
        List<User> userList =  userService.findList(user);
        model.addAttribute("users",userList);
        return "users";
    }

    /**
     * 保存用户信息
    * @author ljz on 2018/4/10 0010
    * @param
    * @return
    */
    @RequestMapping(value="/save",method = RequestMethod.POST)
    public String save(@Valid  User user, BindingResult result){
        System.out.println(user.toString());
        if(result.hasErrors()){
            List<ObjectError> errors = result.getAllErrors();
            for(ObjectError error : errors){
                return error.getCode()+"   "+error.getDefaultMessage();
            }
        }
        int i = userService.save(user);
        return String.valueOf(i);
    }

    @RequestMapping(value="/findOne/{uid}",method = RequestMethod.GET)
    public String findOne(@PathVariable("uid") Long id,Model model){
        User user = userService.findOne(id);
        model.addAttribute("user",user);
        return "user";
    }

    @RequestMapping(value = "update",method = RequestMethod.PUT)
    public String updateUser(@RequestParam("uid") Long id,@RequestParam("uname") String name){
        User user = new User(id,name,20,"43432");
        user.setId(id);
        user.setName(name);
        int i = userService.update(user);
        return String.valueOf(i);
    }

    @RequestMapping(value="/delete/{uid}",method = RequestMethod.DELETE)
    public String delete(@PathVariable("uid") Long id){
        userService.delete(id);
        return null;
    }

    @RequestMapping(value="/updateById",method = RequestMethod.PUT)
    public String updateById(@RequestParam String name,@RequestParam Long id){
        int i = userService.updateById(name,id);
        return String.valueOf(i);
    }
}
